import dayjs from 'dayjs'
Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseItem: {},
    name: '',
    gender: '1',
    mobile: '',
    visitDate:'', // 这个变量专门给请求的接口使用 2023-12-17
    myDateTime: '', // 这个字符串专门给日期组件使用， 事件戳 56515656156156
    minData: new Date().getTime()
  },
  onLoad() {
    this.getHouseList()
  },
  async getHouseList() {
    const res = await wx.http.get('/room')
    console.log(res.data);
    // 一定要加工服务器返回的数据，因为setData设置的数据大小有限制，尽可能设置的数据越小越好，
    const houseList = res.data.map(item => ({id: item.id, name: item.point}))
    this.setData({houseList})
  },
  houseSelect(e){
    console.log(e);
    this.setData({
      houseItem: e.detail
    })
  },
  datetimeConfirm(e) {
    console.log(e);
    this.setData({ 
      visitDate: dayjs(e.detail).format('YYYY-MM-DD'),
      dateLayerVisible: false 
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goPassport() {
    // 要发请求先校验
    if(!this.validateHouseid() || !this.validateName() || !this.validateMobile() || !this.validateDate()) {
      return  // reutrn是退出函数的作用
    }

    const {houseItem: {id: houseId}, name, gender, mobile, visitDate} = this.data
    const res = await wx.http.post('/visitor', {
      houseId: this.data.houseItem.id,
      name: this.data.name,
      gender: this.data.gender,
      mobile: this.data.mobile,
      visitDate: this.data.visitDate
    })
    console.log(res);
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index',
    })
  },
  // 下面是多个校验的函数
  validateHouseid() {
    if(!this.data.houseItem.id) {
      wx.utils.toast('房屋信息必填')
      return false
    }
    return true
  },
  validateName() {
    const pattern = /^[\u4e00-\u9fa5]{2,5}$/
    if(!pattern.test(this.data.name)) {
      wx.utils.toast('姓名必须是2-5位汉字')
      return false
    }
    return true
  },
  validateMobile() {
    const pattern = /^1[3-9]\d{9}$/
    if(!pattern.test(this.data.mobile)) {
      wx.utils.toast('手机号格式错误')
      return false
    }
    return true
  },
  validateDate() {
    if(!this.data.visitDate) {
      wx.utils.toast('访问日期必填')
      return false
    }
    const currentDate = new Date(this.data.visitDate).getTime()
    const futureDate = new Date().getTime() + 3 * 24 * 60 *60 *1000
    console.log(currentDate, futureDate);
    if(currentDate > futureDate) {
      wx.utils.toast('访问日期必须是3天以内')
      return false
    }
    // 选择的时间戳   当前时间+3天的时间戳

    return true
  }
})
